package com.cheney.demo.io;

import org.junit.Test;

import java.io.*;

public class BaseDemo {

	/**
	 * 缓存字节流（按照byte[2048]读取字节流）
	 * @throws Exception
	 */
	@Test
	public void bufferInOutStream() throws Exception{
		//读取文件(缓存字节流)
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("D:/data/temp.txt"));
        //写入相应的文件
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("D:/data/temp2.txt"));
        //读取数据
        //一次性取多少字节
        byte[] bytes = new byte[2048];
        //接受读取的内容(n就代表的相关数据，只不过是数字的形式)
        int n = -1;
        //循环取出数据
        while ((n = in.read(bytes,0,bytes.length)) != -1) {
            //转换成字符串
        	//这里可以实现字节到字符串的转换，比较实用
            String str = new String(bytes,0,n,"utf-8");
            System.out.println(str);
            //写入相关文件
            out.write(bytes, 0, n);
        }
        //清除缓存
        out.flush();
        //关闭流
        in.close();
        out.close();
	}
	
	/**
	 * 缓存字符流（逐行读取字符流）：适合操作读写带编码的文本，很好的解决乱码问题
	 * @throws Exception
	 */
	@Test
	public void bufferReaderWriter() throws Exception{
		//读取文件(字符流)
		//这里主要是涉及中文
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("D:/data/temp.txt"),"utf-8"));
        //BufferedReader in = new BufferedReader(new FileReader("d:\\1.txt")));
        //写入相应的文件
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:/data/temp3.txt"),"utf-8"));
        //BufferedWriter out = new BufferedWriter(new FileWriter("d:\\2.txt"))；
        //读取数据
        //循环取出数据
        String str = null;
        while ((str = in.readLine()) != null) {
            System.out.println(str);
            //写入相关文件
            out.write(str);
            out.newLine();
        }
        
        //清除缓存
        out.flush();
        //关闭流
        in.close();
        out.close();
	}
	
	/**
	 * 缓存字符流（替代BufferedWriter）优点：1自动flush 2不需要newLine 3接受任意类型的参数
	 * @throws Exception
	 */
	@Test
	public void printerWriter() throws Exception{
		//读取文件(字符流)
        Reader in = new InputStreamReader(new FileInputStream("D:/data/temp.txt"),"utf-8");
        //写入相应的文件
        PrintWriter out = new PrintWriter(new FileWriter("D:/data/temp4.txt"));
        //读取数据
        int len = -1;
        while ((len = in.read()) != -1) {
            out.write(len);
        }
        //清楚缓存
        //out.flush();
        //关闭流
        in.close();
        out.close();
	}
}
